package com.threeti.jiayusms.framework.util;

import java.lang.reflect.Field;

import org.hibernate.proxy.AbstractLazyInitializer;
import org.hibernate.proxy.HibernateProxy;

/**
 * ORM工具类
 *
 * @author Jay Meng
 */
public abstract class OrmUtils {

  private static final String HANDLER_FIELD_NAME = "handler";

  public static Object unwrapOrmProxy(final Object objMightbeProxied) {
    if (objMightbeProxied instanceof HibernateProxy) {
      try {
        final Field handlerField = objMightbeProxied.getClass().getDeclaredField(HANDLER_FIELD_NAME);
        handlerField.setAccessible(true);
        final AbstractLazyInitializer handler = (AbstractLazyInitializer) handlerField.get(objMightbeProxied);
        return handler.getImplementation();
      } catch (IllegalAccessException e) {
        throw new AssertionError(e);
      } catch (NoSuchFieldException e) {
        throw new AssertionError(e);
      }
    }

    return objMightbeProxied;
  }

}
